package com.one.blocks.rbac.controller;

import com.one.blocks.mvc.controller.AbstractController;
import com.one.blocks.mvc.request.PageRequest;
import com.one.blocks.mvc.response.ResponseHelper;
import com.one.blocks.mvc.response.WebPageResponse;
import com.one.blocks.mvc.response.WebResponse;
import com.one.blocks.rbac.controller.convert.SysAccountConvert;
import com.one.blocks.rbac.controller.convert.SysUserConvert;
import com.one.blocks.rbac.controller.query.SysUserQuery;
import com.one.blocks.rbac.controller.vo.SysUserGrantRoleVo;
import com.one.blocks.rbac.controller.vo.SysUserGroupVo;
import com.one.blocks.rbac.controller.vo.SysUserLoginVo;
import com.one.blocks.rbac.controller.vo.SysUserVo;
import com.one.blocks.rbac.domain.SysAccount;
import com.one.blocks.rbac.domain.SysRole;
import com.one.blocks.rbac.domain.SysUser;
import com.one.blocks.rbac.domain.SysUserAccount;
import com.one.blocks.rbac.domain.SysUserRole;
import com.one.blocks.rbac.enums.RbacResponseEnum;
import com.one.blocks.rbac.manager.PasswordManager;
import com.one.blocks.rbac.manager.SysMenuManager;
import com.one.blocks.rbac.manager.SysRoleManager;
import com.one.blocks.rbac.manager.SysUserManager;
import com.one.blocks.rbac.manager.SysUserRoleManager;
import com.one.blocks.security.annotation.PreAuthorize;
import com.one.blocks.security.util.SubjectHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.List;
import java.util.Set;

/**
 * @author <a href="mailto:idler41@163.con">idler41</a> created on 2022-05-01 10:06:14
 */
@Api(tags = "系统用户接口")
@RestController
@RequestMapping("/system/user")
@Slf4j
@Validated
public class SysUserController extends AbstractController<SysUserManager, SysUserConvert, SysUser, SysUserVo, SysUserQuery> {

    @Autowired
    private SysRoleManager sysRoleManager;

    @Autowired
    private SysMenuManager sysMenuManager;

    @Autowired
    private PasswordManager passwordManager;

    @Autowired
    private SysUserRoleManager sysUserRoleManager;

    @Autowired
    public SysUserController(SysUserManager manager) {
        super(manager, SysUserConvert.INSTANCE);
    }

    @ApiOperation("查询单个用户")
    @PreAuthorize("system:user:view")
    @GetMapping
    public WebResponse<SysUserVo> get(@Validated @NotNull @RequestParam Integer id) {
        return super.generalGet(id);
    }

    @ApiOperation("根据id批量查询用户")
    @PreAuthorize("system:user:view")
    @GetMapping("/batch")
    public WebResponse<List<SysUserVo>> getIds(@Validated @NotNull @Size(min = 1, max = 100) @RequestParam(name = "ids[]") Set<Integer> ids) {
        return super.generalGetIds(ids);
    }

    @ApiOperation("分页查询用户")
    @PreAuthorize("system:user:view")
    @GetMapping("/page")
    public WebPageResponse<SysUserVo> page(@Validated PageRequest request, @Validated SysUserQuery query) {
        return super.generalPage(request, query);
    }

    @ApiOperation("添加用户")
    @PreAuthorize("system:user:insert")
    @PostMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public WebResponse<Serializable> insert(@Validated @RequestBody SysUserGroupVo sysUserGroupVo) {
        // 密码rsa解密为明文
        String rawPassword;
        try {
            rawPassword = passwordManager.decryptPassword(sysUserGroupVo.getAccount().getPassword());
        } catch (RuntimeException e) {
            return ResponseHelper.fail(RbacResponseEnum.ILLEGAL_PASSWORD);
        }

        // 登录密码加密
        sysUserGroupVo.getAccount().setPassword(passwordManager.encode(rawPassword));

        // 用户、角色、账户
        SysUser sysUser = convert.groupToEntityIgnoreId(sysUserGroupVo);
        List<SysUserRole> sysUserRoleList = convert.groupToSysUserRole(sysUserGroupVo);
        SysAccount sysAccount = SysAccountConvert.INSTANCE.voToEntityIgnoreId(sysUserGroupVo.getAccount());
        SysUserAccount sysUserAccount = convert.toSysUserAccount(sysUserGroupVo);
        manager.insert(sysUser, sysUserRoleList, sysAccount, sysUserAccount);

        return ResponseHelper.success(sysUser.getId());
    }

    @ApiOperation("更新用户(更新所有字段)")
    @PreAuthorize("system:user:update")
    @PutMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public WebResponse<Boolean> update(@Validated @RequestBody SysUserVo sysUserVo) {
        return super.generalUpdate(sysUserVo);
    }

    @ApiOperation("更新用户(只更新非空字段)")
    @PreAuthorize("system:user:update")
    @PatchMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public WebResponse<Boolean> updateSelective(@Validated @RequestBody SysUserVo sysUserVo) {
        return super.generalUpdateSelective(sysUserVo);
    }

    @ApiOperation("删除用户")
    @PreAuthorize("system:user:delete")
    @DeleteMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public WebResponse<Integer> delete(@Validated @NotNull @Size(min = 1, max = 100) @RequestBody Set<Integer> ids) {
        return super.generalDeleteByIds(ids);
    }

    @ApiOperation("登录成功获取用户信息")
    @PreAuthorize("system:user:view")
    @GetMapping(value = "/info", produces = MediaType.APPLICATION_JSON_VALUE)
    public WebResponse<SysUserLoginVo> getInfo() {

        Integer userId = SubjectHelper.getSubjectId();

        SysUser sysUser = manager.get(userId);
        SysUserLoginVo data = new SysUserLoginVo();
        data.setNickName(sysUser.getNickname());
        data.setAvatar(sysUser.getAvatar());

        SysRole sysRole = sysRoleManager.getByUserId(userId);

        data.setPermissions(sysMenuManager.listPermission(sysRole));
        data.setMenus(sysMenuManager.treeSidebar(sysRole));

        return ResponseHelper.success(data);
    }

    @ApiOperation("赋予指定用户指定角色")
    @PreAuthorize("system:user:grant")
    @PostMapping("/grant")
    public WebResponse<Boolean> grant(@Valid @RequestBody SysUserGrantRoleVo sysUserGrantRoleVo) {
        return ResponseHelper.success(sysUserRoleManager.grant(sysUserGrantRoleVo.getUserId(), convert.grantToSysUserRole(sysUserGrantRoleVo)));
    }
}